package net.oschina.archx.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import net.oschina.archx.mybatis.model.Employee;
import net.oschina.archx.mybatis.model.Employee.Gender;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

/**
 * 雇员性别枚举类型处理器
 * 
 * @author ArchX[archx@foxmail.com]
 */
@MappedTypes({Employee.Gender.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class EmployeeGenderTypeHandler extends BaseTypeHandler<Employee.Gender> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Gender parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.name());
    }

    @Override
    public Gender getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getGender(rs.getString(columnName));
    }

    @Override
    public Gender getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getGender(rs.getString(columnIndex));
    }

    @Override
    public Gender getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getGender(cs.getString(columnIndex));
    }

    private Gender getGender(String value) {
        if (value == null)
            return null;
        try {
            return Gender.valueOf(value);
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
}
